package com.cuhk.gulimall.product.app;

import java.util.Arrays;
import java.util.Map;

import com.cuhk.common.valid.AddGroup;
import com.cuhk.common.valid.UpdateGroup;
import com.cuhk.common.valid.UpdateStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import com.cuhk.gulimall.product.entity.BrandEntity;
import com.cuhk.gulimall.product.service.BrandService;
import com.cuhk.common.utils.PageUtils;
import com.cuhk.common.utils.R;


/**
 * 品牌
 *
 * @author chenyujing
 * @email torchsam@aliyun.com
 * @date 2024-06-10 12:02:33
 */
@RestController
@RequestMapping("product/brand")
public class BrandController {
    @Autowired
    private BrandService brandService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = brandService.queryPage(params);
        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{brandId}")
    public R info(@PathVariable("brandId") Long brandId){
		BrandEntity brand = brandService.getById(brandId);
        return R.ok().put("brand", brand);
    }

    /**
     * 保存
     * @Valid是校验规则启动注解
     * 只有加了这个注解，entity类中对各个字段的检查(contraints)才能生效
     * 在形参列表中, 在需要校验的entity对象参数后，紧跟一个BindingResult类型的参数的声明
     * 可以将参数校验的结果(message)存储到这个对象中，便于后续判断并生成规范的响应体
     */
    @RequestMapping("/save")
    public R save(@Validated({AddGroup.class}) @RequestBody BrandEntity brand /*BindingResult bindingResult*/){
        /*
        if(bindingResult.hasErrors()) {
            Map<String, String> map = new HashMap<>();
            bindingResult.getFieldErrors().forEach((item) -> {
               // item -> FieldError
               String errMsg = item.getDefaultMessage();
               String field = item.getField();
               map.put(field, errMsg);
            });
            return R.error(400, "提交的数据不合法").put("data", map);
        }
        else {
            brandService.save(brand);
            return R.ok();
        }
        */
        brandService.save(brand);
        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    public R update(@Validated({UpdateGroup.class}) @RequestBody BrandEntity brand){
		// brandService.updateById(brand);
        brandService.updateCascade(brand);
        return R.ok();
    }

    @PostMapping("/update/status")
    public R updateStatue(@Validated({UpdateStatus.class}) @RequestBody BrandEntity brand) {
        brandService.updateById(brand);
        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody Long[] brandIds){
		brandService.removeByIds(Arrays.asList(brandIds));
        return R.ok();
    }

}
